package timing.ukulele.storage.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import timing.ukulele.common.data.ResponseData;
import timing.ukulele.storage.entity.GroupEntity;
import timing.ukulele.storage.entity.UserEntity;
import timing.ukulele.storage.service.GroupService;
import timing.ukulele.storage.service.UserService;
import timing.ukulele.storage.vo.PageVO;
import timing.ukulele.web.controller.BaseController;

import java.util.List;

/**
 * 用户组相关操作接口
 */
@RestController
@RequestMapping("/group")
@Slf4j
@Tag(name = "用户组相关操作")
public class GroupController extends BaseController {
    private final GroupService groupService;
    private final UserService userService;

    public GroupController(GroupService groupService, UserService userService) {
        this.groupService = groupService;
        this.userService = userService;
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据id获取组信息")
    public ResponseData<GroupEntity> findById(@Parameter(description = "用户组id", required = true, example = "1") @PathVariable("id") String id) {
        GroupEntity group = groupService.findById(id);
        return successResponse(group);
    }

    @GetMapping("/all")
    @Operation(summary = "获取全部组信息")
    public ResponseData<List<GroupEntity>> findAll() {
        List<GroupEntity> groups = groupService.getAll();
        return successResponse(groups);
    }

    @GetMapping("/page/{current}/{size}")
    @Operation(summary = "获取用户组分页信息")
    public ResponseData<PageVO<GroupEntity>> page(@Parameter(description = "当前页", required = true, example = "1") @PathVariable("current") Integer current,
                                                  @Parameter(description = "每页大小", required = true, example = "10") @PathVariable("size") Integer size,
                                                  @Parameter(description = "升序排序列,逗号隔开", example = "id,name") @RequestParam(value = "ascBy", required = false) String ascBy,
                                                  @Parameter(description = "降序排序列,逗号隔开", example = "id,name") @RequestParam(value = "descBy", required = false) String descBy) {
        Sort sort = null;
        if (!StringUtils.hasLength(ascBy) && !StringUtils.hasLength(descBy))
            sort = Sort.by(Sort.Order.desc("_id"));
        if (StringUtils.hasLength(ascBy)) {
            String[] split = ascBy.split(",");
            sort = Sort.by(split).ascending();
        }
        if (StringUtils.hasLength(descBy)) {
            String[] split = descBy.split(",");
            sort = Sort.by(split).descending();
        }
        Page<GroupEntity> page = groupService.getGroupPage(current - 1, size, sort);
        PageVO<GroupEntity> vo = new PageVO<>(current, size, page.getTotalPages(), page.getTotalElements(), page.getContent(), ascBy, descBy);
        return successResponse(vo);
    }

    @PostMapping
    @Operation(summary = "添加一个用户组")
    public ResponseData<GroupEntity> add(@RequestBody GroupEntity group) {
        GroupEntity filter = new GroupEntity();
        filter.setName(group.getName());
        if (groupService.existed(filter)) {
            return failResponse(null, "用户组已存在");
        } else {
            return successResponse(groupService.addGroup(group));
        }
    }

    @PutMapping
    @Operation(summary = "修改用户组信息")
    public ResponseData<GroupEntity> modify(@RequestBody GroupEntity group) {
        GroupEntity filter = new GroupEntity();
        filter.setId(group.getId());
        if (groupService.existed(filter)) {
            try {
                return successResponse(groupService.updateGroup(group));
            } catch (IllegalAccessException e) {
                return failResponse(null, e.getMessage());
            }
        } else {
            return failResponse(null, "用户组不存在");
        }
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户信息")
    public ResponseData<Boolean> delete(@Parameter(description = "用户组id", required = true, example = "1") @PathVariable("id") String id) {
        GroupEntity filter = new GroupEntity();
        filter.setId(id);
        if (groupService.existed(filter)) {
            List<UserEntity> groupUsers = userService.filterByGroup(id);
            if (CollectionUtils.isEmpty(groupUsers))
                return groupService.deleteGroup(id);
            else
                return failResponse(Boolean.FALSE, "请先处理该用户组里用户");
        } else {
            return failResponse(null, "用户组不存在");
        }
    }
}
